import { SDKTools } from "../SDKTools";
import { AliPayAD } from "./AilPayAD";
import { IAd } from "./IAd";
import { KSAD } from "./KSAd";
import { WxMiniAd } from "./WxMiniAd";

export class ADMgr {
    public static AdUnitMap: Map<string, IAd> = new Map();

    private static Is初始化: boolean = false;
    public static start_time: number = -1;// 开始播放时间
    public static end_time: number = -1; // 结束播放时间
    public static clear(){
        this.start_time = -1;
        this.end_time = -1;
    }
    private static InitClass(): IAd {
        if (SDKTools.isdebug) {
            return null;
        }
        if (SDKTools.isAliPay) {
            return new AliPayAD();
        } else if (SDKTools.isWeChat) {
            return new WxMiniAd();
        } else if (SDKTools.isKSGame) {
            return new KSAD();
        }
        return null;
    }

    public static 初始化广告位(adUnitIds: string[]) {
        if (SDKTools.isdebug) return
        console.log("xxzzz1",adUnitIds.length,Array.from(this.AdUnitMap.keys())[0]);
        if (this.Is初始化) return;
        console.log("xxzzz2",Array.from(this.AdUnitMap.keys()).length,Array.from(this.AdUnitMap.keys())[0]);
        this.Is初始化 = true;
        for (let i = 0; i < adUnitIds.length; i++) {
            const adUnitId = adUnitIds[i];
            let adUnit = this.InitClass();
            adUnit.func_初始化({ adUnitId: adUnitId });
            this.AdUnitMap.set(adUnitId, adUnit);
            console.log(`func_初始化${adUnitId}zz`)
        }
        console.log("xxzzz3",Array.from(this.AdUnitMap.keys()).length,Array.from(this.AdUnitMap.keys())[0]);
    }

    public static GetAdUnit(adUnitId: string) {
        return this.AdUnitMap.get(adUnitId);
    }

    public static async PlayAd(opt: {
        adUnitId: string,
        showLoading: boolean,
        showError: boolean,
    }) {
        // 是否是debug模式
        if (SDKTools.isdebug) return { res: 1, errMsg: "debug" };
        let { adUnitId, showLoading, showError } = opt;
        console.log("xx",Array.from(this.AdUnitMap.keys()).length,Array.from(this.AdUnitMap.keys())[0]);
        let adUnit = this.GetAdUnit(adUnitId);
        let msg = "【广告】adUnitId = " + adUnitId;
        console.info(msg);
        if (adUnit) {
            let dat = await adUnit.PlayAd({ showLoading: showLoading, showError: showError });
            return dat
        } else {
            let errMsg = "没有找到广告:" + adUnitId;
            console.error("没有找到广告单元", adUnitId);
            if (showError) {
                SDKTools.m_ADClass.showModal({ content: errMsg } as any);
            }
            return {
                res: 0,
                errMsg: errMsg,
            };
        }
    }
}